﻿using DeviceCommons.DataHandling;
using DeviceCommons.DeviceMessages.Abstractions;
using DeviceCommons.DeviceMessages.Models.V1;

namespace DeviceCommons.DeviceMessages.Serialization.V1.Parsers
{
    public class DeviceMessageInfoParser : AbstractMessageParser<IDeviceMessageInfo>, IDeviceMessageInfoParser
    {
        public DeviceMessageInfoParser() : base(new DeviceMessageInfo())
        {

        }

        public override IDeviceMessageInfo Parser(ReadOnlySpan<byte> bytes)
        {
            IDeviceMessageInfo model = new DeviceMessageInfo();

            byte didLength = bytes[0];
            int currentIndex = 1;


            if (didLength > 0)
            {
                model.DIDBytes = bytes.Slice(currentIndex, didLength).ToArray();
                currentIndex += didLength;
            }
            else model.DIDBytes = [];

            model.DeviceType = bytes[currentIndex];
            currentIndex++;


            int readingsDataLength = bytes.Length - currentIndex;
            if (readingsDataLength > 0)
            {
                model.Reading ??= DeviceMessageSerializerProvider.InfoReadingsV1Par.Parser(bytes.Slice(currentIndex, readingsDataLength));
            }
            else model.Reading = new DeviceMessageInfoReadings();
            Model = model;
            return model;
        }
    }
}
